package com.chushouya.manager.dao.repository;


import com.general.framework.core.lang.Longs;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.manager.dao.entity.AttachmentEntity;
import com.chushouya.manager.dao.mapper.AttachmentEntityMapper;
import com.chushouya.manager.dto.admin.attachment.AttachmentQuery;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Repository
public class AttachmentRepository extends BaseRepository<AttachmentEntityMapper, AttachmentEntity, Long> {

    public PageResult<AttachmentEntity> selectPageResult(AttachmentQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public List<AttachmentEntity> selectList(AttachmentQuery query) {
        return this.selectByExample(this.buildExample(query));
    }

    public AttachmentEntity selectOne(AttachmentQuery query) {
        return this.selectFirstOneByExample(this.buildExample(query));
    }

    public AttachmentEntity selectOneWithProperties(Long attachmentId, String... properties) {
        AttachmentQuery query = new AttachmentQuery();
        query.setAttachmentId(attachmentId);
        final Example example = this.buildExample(query);
        example.selectProperties(properties);
        return this.selectFirstOneByExample(example);
    }

    private Example buildExample(AttachmentQuery query) {
        Example example = buildExample();
        if (Longs.notNullAndZero(query.getAttachmentId())) {
            example.and().andEqualTo("attachmentId", query.getAttachmentId());
        }
        if (Longs.notNullAndZero(query.getDirectoryId())) {
            example.and().andEqualTo("directoryId", query.getDirectoryId());
        }
        if (Strings.isNotBlank(query.getAttachmentName())) {
            example.and().andLike("attachmentName", Strings.format("%{}%", query.getAttachmentName()));
        }
        if (Strings.isNotBlank(query.getMimeType())) {
            example.and().andEqualTo("mimeType", query.getMimeType());
        }
        if (Objects.nonNull(query.getStatus())) {
            example.and().andEqualTo("status", query.getStatus());
        }
        if (Strings.isNotBlank(query.getHandleUser())) {
            example.and().andLike("handleUser", Strings.format("%{}%", query.getHandleUser()));
        }
        if (Objects.nonNull(query.getStartTime()) && Objects.nonNull(query.getEndTime())) {
            example.and().andBetween("createTime", query.getStartTime(), query.getEndTime());
        }
        example.orderBy("attachmentId").desc();
        return example;
    }
}
